package com.jsm.tf.net;

import com.jsm.tf.net.handler.ClientMessageHandler;
import com.jsm.tf.net.handler.IdleStateEventHandler;
import com.jsm.tf.net.protocol.MessageCodec;
import com.jsm.tf.net.protocol.ProtocolFrameDecoder;
import com.jsm.tf.net.protocol.serialize.Serializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.net.InetSocketAddress;

@Component
@Slf4j
public class NettyServer {

    public static final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);

    /**
     * @Fields boss : boss 线程组用于处理连接工作, 默认是系统CPU个数的两倍，也可以根据实际情况指定
     */
    private EventLoopGroup boss = new NioEventLoopGroup();

    /**
     * @Fields work : work 线程组用于数据处理, 默认是系统CPU个数的两倍，也可以根据实际情况指定
     */
    private EventLoopGroup work = new NioEventLoopGroup();
    @Resource
    private ClientMessageHandler clientMessageHandler;
    @Resource
    private IdleStateEventHandler idleStateEventHandler;
    @Resource
    private Serializer serializer;
    @Value("${netty.client.heartbeat.interval:5}")
    private int heartbeatInterval;
    /**
     * @Fields port : 服务端端口
     */
    @Value("${netty.server.port:8888}")
    private int port;


    @PostConstruct
    public void start() throws InterruptedException {

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(boss, work)
                // 指定Channel
                .channel(NioServerSocketChannel.class)
                // 使用指定的端口设置套接字地址
                .localAddress(new InetSocketAddress(port))

                // 服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                .option(ChannelOption.SO_BACKLOG, 1024)

                // 设置TCP长连接,一般如果两个小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
                .childOption(ChannelOption.SO_KEEPALIVE, true)

                // 将小的数据包包装成更大的帧进行传送，提高网络的负载,即TCP延迟传输
                .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ProtocolFrameDecoder());
                        ch.pipeline().addLast(LOGGING_HANDLER);
                        ch.pipeline().addLast(new MessageCodec(serializer));
                        ch.pipeline().addLast(new IdleStateHandler(heartbeatInterval * 3 + 1, 0, 0));
                        //ChannelDuplexHandler可以同时作为入站和出站处理器
                        ch.pipeline().addLast(idleStateEventHandler);
                        ch.pipeline().addLast(clientMessageHandler);
                    }
                });

        ChannelFuture future = bootstrap.bind().sync();

        if (future.isSuccess()) {
            log.info("启动 Netty Server...");
        }
    }

    @PreDestroy
    public void PreDestroy() throws InterruptedException {
        boss.shutdownGracefully().sync();
        work.shutdownGracefully().sync();
        log.info("关闭Netty...");
    }
}
